<?php


namespace app\admin\controller\system;

use app\admin\controller\BaseController;
use app\common\exception\MessageException;
use app\common\model\mysql\system\Role as RoleModel;
use app\common\validate\IDMustBePositiveInt;

class Role extends BaseController
{
    // 列表所有
    public function list()
    {
        try {
            $params = $this->request->param();
            $result = RoleModel::list($params);

            return $this->renderSuccess($result);
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function create()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不允许']);
        }
        $data = $this->request->param();
        try {

            $name = RoleModel::checkName($data['name']);

            if ($name) {
                return $this->renderFail('角色已存在');
            }

            $data['status'] = 1;

            $result = RoleModel::add($data);
            return $this->renderSuccess($result, '添加成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function update()
    {
        if (!$this->request->isPost()) {
            throw new MessageException(['msg' => '请求方法不合法']);
        }

//        (new ProductCategoryValidate())->goCheck();
        $params = $this->request->param();

        if (!$params['id']) {
            return $this->renderFail('角色不存在');
        }

        try {
            $findData = RoleModel::checkName($params['name'], $params['id']);
            if ($findData) {
                return $this->renderFail('角色已存在');
            }

            $data = RoleModel::edit($params);

            return $this->renderSuccess($data, '更新成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }

    public function delete()
    {
        (new IDMustBePositiveInt())->goCheck();
        $params = $this->request->param();

        try {
            $findData = RoleModel::where('id', $params['id'])->find();

            if (!$findData) {
                return $this->renderFail('角色不存在');
            }
            // 删除
            RoleModel::remove($params);
            return $this->renderSuccess([], '删除成功');
        } catch (\Exception $e) {
            throw new MessageException(['msg' => $e->getMessage()]);
        }
    }
}